<template>
  <div class="login">
    <el-form
      class="form"
      ref="ruleFormRef"
      style="max-width: 300px"
      :model="formData"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(ruleFormRef)" class="login-button"
          >登录</el-button
        >
        <el-button @click="onReset(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/UserStore'
import { login } from '@/api/UserApi'
import router from '@/router'
interface RuleForm {
  name: string
  password: string
}
const formData = reactive({
  name: '吱吱吱吱',
  password: 'QQQqqq123',
})
const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: string, callback: (err?: Error) => void) => {
  if (!/^(?=\D+\d)(?=.*[a-z])(?=.*[A-Z])\w{3,18}$/.test(value)) {
    callback(new Error('密码必须是非数字开始，包含大小写字母和数字'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 7, message: '用户名长度为2到7个字符', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    { validator: validatePass, trigger: 'blur' },
  ],
})

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const loginData = await login(formData.name, formData.password)
      console.log(loginData)
      const store = useUserStore()
      store.token = loginData.data.token
      const data = { ...loginData.data }
      delete data.token
      store.userInfo = { ...data }
      router.push({ name: 'main' })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const onReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.login {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  min-height: 200px;
  border: 2px solid #eee;
  width: 500px;
}
.form {
  margin: 30px auto 0;
}
.login-button {
  margin: 10px 60px 0 40px;
}
</style>
